<template>
  <a-modal
    title="授权数据"
    :width="600"
    :visible="visible"
    :confirmLoading="confirmLoading"
    @ok="handleSubmit"
    @cancel="handleCancel"
  >
    <a-spin :spinning="formLoading">
      <a-form :form="form">
        <a-form-item
          label="授权范围"
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
          has-feedback
        >
          <a-select style="width: 100%" placeholder="请选择授权范围" v-decorator="['dataScopeType', {rules: [{ required: true, message: '请选择授权范围！' }]}]" >
            <a-select-option v-for="(item,index) in dataScopeTypeData" :key="index" :value="item.code" @click="handleChange(item.code)">{{ item.value }}</a-select-option>
          </a-select>
        </a-form-item>
        <!--班组选择-->
        <template v-if="showTeamTable">
          <a-row >
            <a-col :span="15">
              <!--搜索框--弹窗-->
              <a-input
                @keyup.enter="searchMember"
                :maxLength="11"
                style="width: 100%;margin-bottom: 10px;"
                placeholder="请输入姓名"
                v-model="search_value">
              </a-input>
            </a-col>
            <a-col :span="5">
              <a-button type="primary" style="width: 100%;" @click="searchMember" icon="search">搜索</a-button>
            </a-col>
          </a-row>
          <a-table
            :row-selection="{ selectedRowKeys: selectedRowKeys, onChange: onSelectChange,columnWidth:40 ,getCheckboxProps:getCheckboxProps}"
            size="small"
            :pagination="pagination"
            :columns="columns"
            :dataSource="tableList"
            :rowKey="(record, index) => record.teamId"
            @change="handleTableChange"
          >
            <!--序号-->
            <template slot="index" slot-scope="text, record, index">
              <span>{{ (pagination.current - 1) * pagination.pageSize + (index + 1) }}</span>
            </template>
          </a-table>
        </template>
        <div v-show="orgTreeShow">
          <a-form-item
            label="选择机构"
            :labelCol="labelCol"
            :wrapperCol="wrapperCol"
          >
            <a-tree
              v-model="checkedKeys"
              checkable
              checkStrictly
              :auto-expand-parent="autoExpandParent"
              :expanded-keys="expandedKeys"
              :tree-data="orgTreeData"
              :selected-keys="selectedKeys"
              :replaceFields="replaceFields"
              @expand="onExpand"
              @select="onSelect"
            />
          </a-form-item>
        </div>
      </a-form>
    </a-spin>
  </a-modal>
</template>

<script>
import {getOrgTree} from '@/api/modular/system/orgManage'
import {sysRoleGrantData, sysRoleOwnData,findAllHasteamByRoleId} from '@/api/modular/system/roleManage'
import {sysDictTypeDropDown} from '@/api/modular/system/dictManage'
import { getNoTeamList} from '@/api/bd/team'

export default {
  data () {
      return {
        tableList:[],
        allTeamTable:[],
        hasTeamTable:[],
        originMenberTableList:[],
        selectedRowKeys:[],
        hasTeamRowKeys:[],
        search_value:'',
        labelCol: {
          style: { 'padding-right': '20px' },
          xs: { span: 24 },
          sm: { span: 5 }
        },
        wrapperCol: {
          xs: { span: 24 },
          sm: { span: 15 }
        },
        orgTreeData: [],
        expandedKeys: [],
        checkedKeys: [],
        visible: false,
        confirmLoading: false,
        formLoading: true,
        autoExpandParent: true,
        selectedKeys: [],
        subValues: [],
        roleEntity: [],
        dataScopeTypeData: [],
        orgTreeShow: false,
        replaceFields: {
          key: 'id'
        },
        form: this.$form.createForm(this),
        columns: [
          { title: '序号', align:'center', scopedSlots: { customRender: 'index' }, width: 50 },
          { title: '班组类型', align:'center', dataIndex: 'teamTypeName' ,width: 100},
          { title: '班组名称', align:'center', dataIndex: 'teamName', width: 100 },
          { title: '组长ID', align:'center', dataIndex: 'teamLeaderId',width: 100},
          { title: '组长姓名', align:'center', dataIndex: 'teamLeader',width: 100,ellipsis:true },
          // { title: '是否禁用', dataIndex: 'isDisabled', align:'center', width: 90, customRender: (text) => {return text == 0 ? '否' : '是'}},
        ],
        pagination: {
          current: 1, //当前页
          pageSize: 10, //当前页数
          total: 0, //总条数
          pageSizeOptions: ['10', '20', '30'], //这里注意只能是字符串，不能是数字
          showTotal: (total) => `共${total}条`, //分页中显示总的数据
        },
        showTeamTable:false
      }
    },
  mounted() {
  },
  methods: {
    getNoTeamList() {
      const roleId = this.roleEntity.id
      getNoTeamList({ roleId: roleId }).then((res) => {
        this.allTeamTable = res.rows
        this.originMenberTableList = res.rows
        this.tableList=this.hasTeamTable.concat(this.allTeamTable)
      })
    },
    hasTeamByRoleId() {
      const roleId = this.roleEntity.id
      findAllHasteamByRoleId({ roleId: roleId }).then(res => {
        this.hasTeamTable = res.rows
        this.hasTeamTable.forEach(item=> this.hasTeamRowKeys.push(item.teamId))
      })
      this.getNoTeamList()
    },
    isInculdeId(teamId){
      const len = this.hasTeamTable.length
      let result = false
      for(let i=0;i<len;i++){
        if(this.hasTeamTable[i].teamId==teamId){
          result=true
          break
        }
      }
      return result
    },
    getCheckboxProps(record) {
      return ({
        props: {
          defaultChecked: this.hasTeamRowKeys.includes(record.teamId) ? true :false
        }
      })
    },
    /**
     * 查找成员
     * **/
    searchMember() {
      if (!this.search_value || this.search_value == '') {
        this.allTeamTable = this.originMenberTableList
      }else{
        this.allTeamTable = this.allTeamTable.filter(item => {
          return item.teamName.indexOf(this.search_value) > -1 || item.teamLeader.indexOf(this.search_value) > -1
        })
      }
      // console.log('过滤的数据：', this.allTeamTable)
      this.tableList = this.hasTeamTable.concat(this.allTeamTable)
    },

    /**
     * 勾选成员
     * **/
    onSelectChange(selectedRowKeys) {
      this.selectedRowKeys = selectedRowKeys
    },
    handleTableChange(pagination) {
      this.pagination.current = pagination.current
      this.pagination.pageSize = pagination.pageSize
    },
    // 初始化方法
    roleOrg(record) {
      this.roleEntity = record
      this.visible = true
      this.formLoading = true
      this.selectedRowKeys = []
      this.hasTeamRowKeys=[]
      this.tableList = []
      this.allTeamTable = []
      this.hasTeamTable = []
      this.sysDictTypeDropDown()
      this.form.getFieldDecorator('dataScopeType', { initialValue: record.dataScopeType.toString() })

      this.handleChange(record.dataScopeType)
    },
    /**
     * 获取字典数据
     */
    sysDictTypeDropDown() {
      // 数据范围
      sysDictTypeDropDown({ code: 'data_scope_type' }).then((res) => {
        // console.log('数据范围',res)
        this.dataScopeTypeData = res.data
        this.dataScopeTypeData.push({
          code: '6',
          value: '仅班组数据'
        })
        this.formLoading = false
      })
    },

    // 范围下拉框事件
    handleChange(value) {

      if (value == '6') {
        this.orgTreeShow = false
        this.showTeamTable = true
        this.hasTeamByRoleId()
        return
      }
      this.showTeamTable = false
      // eslint-disable-next-line eqeqeq
      if (value == '5') {
        this.formLoading = true
        this.orgTreeShow = true
        // 获取机构树
        this.getOrgTree()
        // 已关联数据
        this.sysRoleOwnData(this.roleEntity)
      } else {
        this.orgTreeShow = false
        // 清理已选中机构
        this.checkedKeys = []
      }
    },

    /**
     * 获取机构树
     */
    getOrgTree() {
      getOrgTree().then((res) => {
        if (res.success) {
          this.orgTreeData = res.data
          // 默认展开
          this.orgTreeData.forEach(item => {
            this.expandedKeys.push(item.id)
          })
        }
      })
    },

    /**
     * 此角色已有数据列表
     */
    sysRoleOwnData(record) {
      sysRoleOwnData({ id: record.id }).then((res) => {
        if (res.success) {
          this.checkedKeys = res.data
        }
        this.formLoading = false
      })
    },

    onExpand(expandedKeys) {
      this.expandedKeys = expandedKeys
      this.autoExpandParent = false
    },
    onCheck(checkedKeys) {
      this.checkedKeys = checkedKeys
    },
    onSelect(selectedKeys, info) {
      this.selectedKeys = selectedKeys
    },

    handleSubmit() {
      const { form: { validateFields } } = this
      this.confirmLoading = true
      validateFields((errors, values) => {
        if (!errors) {

          const checkedKeys = this.checkedKeys.checked === undefined ? this.checkedKeys : this.checkedKeys.checked
          const params = {
            id: this.roleEntity.id,
            grantOrgIdList: checkedKeys,
            dataScopeType: values.dataScopeType,
            teamIdList:this.selectedRowKeys
          }
          // console.log('提交的参数：',params)
          sysRoleGrantData(params).then((res) => {
            this.confirmLoading = false
            if (res.success) {
              this.$message.success('授权成功')
              this.$emit('ok', values)
              this.handleCancel()
            } else {
              this.$message.error('授权失败：' + res.message)
            }
          }).finally((res) => {
            this.confirmLoading = false
          })
        } else {
          this.confirmLoading = false
        }
      })
    },
    handleCancel() {
      this.form.resetFields()
      // 清空已选择的
      this.checkedKeys = []
      // 清空已展开的
      this.expandedKeys = []
      this.visible = false
      // 隐藏机构树
      this.orgTreeShow = false
    }
  }
  }
</script>

<style scoped>
/deep/ .ant-table-small > .ant-table-content > .ant-table-body {
  margin: 0px
}
</style>